/**
 * Created by hjx on 2018/2/7.
 */
(function () {
    var exports = this;

    var $ = null;
    var javaClubInfoItem = cc.Layer.extendEX({
        layerWidth: 0,
        _data :null ,
        ctor: function (data) {
            this._super();
            var that = this;
            var scene = ccs.load(res.javaClubInfoItem_json, getCCSFileNamePath(res.javaClubInfoItem_json));
            this.addChild(scene.node);
            $ = create$(this.getChildByName('Layer'));

            this.layerWidth = this.getChildByName('Layer').getBoundingBox().width;
            
            TouchUtil.setOnclickListener($('btn_in_club'), function () {
                that.enterClub(data._id);
            }, {swallowTouches: false});
            this.initUI(data);
        },
        initUI:function (data) {
            this._data = data ;
            $('lb_name').setString(ellipsisStr(data.name, 10));
            $('lb_qz').setString(ellipsisStr(data.nick, 5));
            $('lb_id').setString('' + data._id);
            $('lb_players').setString(data.players_count || '');
            $('tableNum').setString(data.room_cnt || '0');
            loadImageToSprite(data.head, $('head'), true);
        },
        getLayerWidth: function () {
            return this.layerWidth;
        },
        enterClub: function (clubId) {
            cc.sys.localStorage.setItem('SelectClub', clubId);
            gameData.CULBID = clubId;
            showBoard('javaClubBorad');

        }
    });


    var javaClubTableItem = cc.TableViewCell.extend({
        layerHeight: 0,
        layerWidth: 0,
        roomInfo1: null,
        roomInfo2: null,
        posArr3: [],
        _data1:null ,
        _data2:null ,
        _pos:null ,
        _idx:null ,
        

        //根据玩家人数 显示不同位置的加入文字
        _btnJoinView: {
            2: [1, 3],
            3: [4, 1, 2],
            4: [1, 2, 3, 4],
            5: [1, 2, 3, 4, 5],
        },

        ctor: function () {
            this._super();
            var that = this;
            
        
            this.posArr3 = [cc.p(42.00, 212.00), cc.p(41, 322), cc.p(251, 322)];
        
            var scene = ccs.load(res.ClubTableItem_json, getCCSFileNamePath(res.ClubTableItem_json));
            this.addChild(scene.node);
            $ = create$(this.getChildByName('Layer'));

            

            this.layerWidth = this.getChildByName('Layer').getBoundingBox().width;
            this.layerHeight = this.getChildByName('Layer').getBoundingBox().height;


           

            var startPos = null;
            TouchUtil.setOntouchListener($('touch1'), undefined, {
                onTouchBegan: function (node, touch) {
                    startPos = $('touch1').convertToWorldSpace(cc.p(0, 0));
                },
                onTouchEnded: function (node, event) {
                    var time = new Date().getTime();
                    if (Math.abs(gameData.clickClubRoomTime - time) <= 1000) {
                        return;
                    }
                    gameData.clickClubRoomTime = time;
                    var endPos = $('touch1').convertToWorldSpace();
                    if (Math.abs(endPos.x - startPos.x) <= 50) {
                        if (that._data1 && that._data1.room_id) { //不是空桌子
                            var func = function () {
                                showLoading('正在加入房间');
                                network.send(3002, {
                                    room_id: '' + that._data1.room_id
                                });
                            };
                            if (pos == 5) {
                                cc.director.getRunningScene().addChild(new ClubEnterGame(that._data1, func));
                            } else {
                                func();
                            }
                        } else { //是空桌子
                            var info = that.roomInfo1;
                            if (!info) {
                                info = getClubCurrentWanfaInfo();
                            }
                            if (info) { //有info创建或者进入房间
                                that.createOrEnterRoom(info, that._pos, that._idx);
                            }
                        }
                    }
                },
                swallowTouches: false
            });
            TouchUtil.setOntouchListener($('touch2'), undefined, {
                onTouchBegan: function (node, touch) {
                    startPos = node.convertToWorldSpace(cc.p(0, 0));
                },
                onTouchEnded: function (node, event) {
                    var time = new Date().getTime();
                    if (Math.abs(gameData.clickClubRoomTime - time) <= 1000) {
                        return;
                    }
                    gameData.clickClubRoomTime = time;
                    var endPos = node.convertToWorldSpace(cc.p(0, 0));
                    if (Math.abs(endPos.x - startPos.x) <= 50) {
                        if (that._data2 && that._data2.room_id) {
                            var func = function () {
                                showLoading('正在加入房间');
                                network.send(3002, {
                                    room_id: '' + that._data2.room_id
                                });
                            };
                            if (pos == 5) {
                                cc.director.getRunningScene().addChild(new ClubEnterGame(that._data2, func));
                            } else {
                                func();
                            }
                        } else {
                            var info = that.roomInfo2;
                            if (!info) {
                                info = getClubCurrentWanfaInfo();
                            }
                            if (info) { //有info创建或者进入房间
                                that.createOrEnterRoom(info, that._pos, that._idx);
                            }
                        }
                    }
                },
                swallowTouches: false
            });
   

            return true;
        },
        initUI:function (data1, data2, pos, count, idx, clubid, parent, inRoomLayer) {
            this._data1 = data1 ;
            this._data2 = data2 ;
            this._pos = pos ;
            this._idx = idx ;
            var that =this ;
            if (data1['roomInfo']) {
                that.roomInfo1 = data1['roomInfo'];
                data1 = data1['roomData'];
            }

            if (data2['roomInfo']) {
                that.roomInfo2 = data2['roomInfo'];
                data2 = data2['roomData'];
            }

            if (data1) {
                this.setTableDesk(data1, 1);
            } else {
                this.setTableDesk(this.roomInfo1, 1);
            }

            if (data2) {
                this.setTableDesk(data2, 2);
            } else {
                if (pos == 5 && this.roomInfo2.tag == undefined) {
                    $('table1').setVisible(false);
                }
                this.setTableDesk(this.roomInfo2, 2);
            }
            var upCellView = that.initTableUI(data1, $('table0'), that.roomInfo1, pos, true);
            that.initTableUI(data2, $('table1'), that.roomInfo2, pos, upCellView);
        },
        //进入房间
        createOrEnterRoom: function (info, pos, idx) {
            var options = info.options;
            if (_.isString(options)) {
                options = JSON.parse(options);
            }
            var dataPos = info.pos; //桌子的 楼层
            if (dataPos == undefined) {
                return;
            }
            options.pos = dataPos;
            options.place = 2 * idx;
            options.desp = info.desc;
            options['remarks'] = info['remarks'];
            if (options['wanjiarenshu0'])
                delete options['wanjiarenshu0'];
            if (options['wanjiarenshu1'])
                delete options['wanjiarenshu1'];
            if (options['wanjiarenshu2'])
                delete options['wanjiarenshu2'];
            if (options['wanjiarenshu3'])
                delete options['wanjiarenshu3'];
            if (options['wanjiarenshu4'])
                delete options['wanjiarenshu4'];
            showLoading('正在加入房间');
            gameData.last3001Data = {
                room_id: 0
                , club_id: options['club_id']
                , map_id: options['mapid']//gameData.appId
                , mapid: options['mapid']
                , daikai: true
                , options: options
                , timestamp: getCurTimestampMills()
            };
            network.send(3001, gameData.last3001Data);
        },
        //牌局中返回俱乐部查看
        isRoomReturn: function (data, endPos, inRoomLayer, parent) {
            if (data && data.room_id == gameData.roomId) {
                //是我所在的房间 ，返回和解散处理
                parent.showRoomSetting(data, endPos, gameData.uid, inRoomLayer);
            } else {
                if (gameData.mapId < 300) {
                    showClubAlert('是否退出当前房间, 加入其他房间？', function () {
                        network.send(3003, {room_id: gameData.roomId});
                    }, function () {
                    });
                } else {
                    showClubAlert('是否退出当前房间, 加入其他房间？', function () {
                        network.sendPhz(3003, 'Quit/' + gameData.roomId);
                    }, function () {
                    });
                }
            }
        },
        //判断是否禁玩
        isForbidPlay: function (clubInfo) {
            //判断是否禁玩
            var black_list = clubInfo.black_list || [];
            if (black_list.length > 0) {
                var isfind = _.filter(black_list, function (uid) {
                    return gameData.uid == uid;
                });
                if (isfind.length > 0) {
                    showClubAlert('你已被管理员禁玩,请联系管理员');
                    return true;
                }
                return false;
            }
            return false;
        },
        /**
         * 初始化桌子
         * @param data          桌子数据
         * @param node          桌子节点
         * @param roomInfo      房间信息
         * @param pos           桌子位置
         * @param upCellView    上一个桌子是否显示 (这个参数指针对 table1节点的桌子生效 )
         * @returns {boolean}   本次是否成功显示桌子
         */
        initTableUI: function (data, node, roomInfo, pos, upCellView) {
            var that = this;
            for (var i = 1; i <= 9; i++) {
                if (!$('row' + i, node)) break;
                $('row' + i, node).setVisible(false);
            }
            for (var i = 1; i <= 4; i++) {
                if ($('btn_joinTable' + i, node)) {
                    $('btn_joinTable' + i, node).setVisible(false);
                }
            }


            safeHide($('idx_sp', node));
            $('lb_name', node).setVisible(false);
            $('lb_plaeyrs', node).setVisible(false);
            if (data && data.room_id) {
                $('lb_num', node).setString('房号:' + data.room_id);
                $('lb_num', node).setVisible(true);
                var options = data.option;
                if (_.isString(data.option)) {
                    options = JSON.parse(options);
                }
                $('lb_plaeyrs', node).setString(data['nicknames'].length + '/' + data['max_player_cnt'] + '人');
                if (data.status == 2) {
                    $('lb_plaeyrs', node).x = 106;
                    $('lb_plaeyrs', node).setVisible(true);
                    $('lb_progress', node).setVisible(true);

                    var str = (data.map_id >= 3000 ? (!data.used ? 1 : (data.used + 1)) : data.used)
                        + '/' + (options.rounds || options.jushu);
                    str += '局';
                    $('lb_progress', node).setString(str);
                } else {
                    $('lb_progress', node).setVisible(false);
                    $('bg_progress', node).setVisible(false);
                    $('lb_plaeyrs', node).setVisible(false);
                }
                $('state', node).setVisible(false);

                var jonViews = this._btnJoinView[data['max_player_cnt']];
                for (var i = 0; i < jonViews.length; i++) {
                    $('btn_joinTable' + jonViews[i], node).setVisible(true);
                }

                for (var i = 1; i <= data.nicknames.length; i++) {
                    if ($('row' + i, node)) {
                        $('row' + i, node).setVisible(true);
                        $('btn_joinTable' + jonViews[(i - 1)], node).setVisible(false);
                        loadImageToSprite(data.heads[i - 1], $('row' + i + '.head', node), true);
                        $('row' + i + '.lb_name', node).setString(ellipsisStr(data.nicknames[i - 1], 6));
                    } else {
                        break;
                    }
                }
                if (roomInfo.tag && roomInfo.tag == 1) { //混合玩法
                    $('state', node).setVisible(false);
                    $('lb_name', node).setVisible(true);

                    var viewStr = data.option['remarks'];
                    if (viewStr == null || viewStr.length == 0) {
                        viewStr =gameData.mapId2Name(parseInt(data.map_id));
                    }
                    $('lb_name', node).setString(ellipsisStr(viewStr, 6));
                    if (pos == 5) {
                        var dataPos = data.option.pos;
                        var idx = pos - dataPos;
                        var idx_sp = $('idx_sp', node);
                        if (idx > 0 && idx < 5) {
                            idx_sp.setVisible(true);
                            idx_sp.setTexture(res['club_icon_wanfa' + idx]);
                        }
                    }
                } 
                return true;
            } else {
                $('state', node).setVisible(true);
                $('lb_num', node).setVisible(false);
                $('lb_progress', node).setVisible(false);
                $('bg_progress', node).setVisible(false);
               

                //这里用语处理多余的桌子不显示   也就是只显示 一个加入房间的桌子即可
                //一共两个情况。
                //第一 上面的桌子有数据  下面的桌子没有数据的情况下  一定是下面的桌子显示加入。
                //第二 前面的桌子都有数据  上面的桌子没有数据
                // if(!roomInfo.tag && node.getName() == 'table1' && !upCellView){
                //     node.setVisible(false);
                // }
                node.setVisible(false);
                if (roomInfo.tag && roomInfo.tag == 1) {
                    node.setVisible(true);
                    $('state', node).setVisible(false);
                    $('lb_name', node).setVisible(true);
                    var remarks = roomInfo.remarks;
                    var viewStr = remarks;
                    if (viewStr == null || viewStr.length == 0) {
                        viewStr = gameData.mapId2Name(parseInt(roomInfo.map_id));

                    }
                    $('lb_name', node).setString(ellipsisStr(viewStr, 6));
                    if (pos == 5) {
                        var idx = 5 - roomInfo.pos;
                        var idx_sp = $('idx_sp', node);
                        if (idx > 0 && idx < 5) {
                            idx_sp.setVisible(true);
                            idx_sp.setTexture(res['club_icon_wanfa' + idx]);
                        }
                    }
                    return true;
                }
            }
            return false;
        },
        //设置头像位置
        setTableDesk: function (data, type, playersNum) {
            var wanfaObj = data;
            // var desc = wanfaObj.desc || wanfaObj.wanfa || wanfaObj.option.desp;
            var playerCount = club.getMaxPlayerNum(wanfaObj);
            if (playersNum) {
                playerCount = playersNum;
            }

            if (type == 1) {
                $('table0').setTexture(res['club_table_for' + playerCount]);
            } else {
                $('table1').setTexture(res['club_table_for' + playerCount]);
            }
            if (playerCount == 5) {
            }
            if (playerCount == 3) {
                if (type == 1) {
                    $('table0').setTexture(res.club_table_for3);
                    $('table0.row1').setPosition(this.posArr3[0]);
                    $('table0.row2').setPosition(this.posArr3[1]);
                    $('table0.row3').setPosition(this.posArr3[2]);
                } else {
                    $('table1').setTexture(res.club_table_for3);
                    $('table1.row1').setPosition(this.posArr3[0]);
                    $('table1.row2').setPosition(this.posArr3[1]);
                    $('table1.row3').setPosition(this.posArr3[2]);
                }
            } else if (playerCount == 2) {
                if (type == 1) {
                    $('table0.row1').setPosition($('table0.row1').getPosition());
                    $('table0.row2').setPosition($('table0.row3').getPosition());
                    $('table0').setTexture(res.club_table_for2);
                } else {
                    $('table1').setTexture(res.club_table_for2);
                    $('table1.row1').setPosition($('table1.row1').getPosition());
                    $('table1.row2').setPosition($('table1.row3').getPosition());
                }

            }
        },

        getLayerWidth: function () {
            return this.layerWidth;
        },
        getLayerHeight: function () {
            return this.layerHeight;
        }
    });
    
    exports.javaClubInfoItem = javaClubInfoItem;
    exports.javaClubTableItem = javaClubTableItem;
})(window);